package com.k4b.Bib;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class WebPageImporter {
//	http://biblia.info.pl/ - 12 tłumaczeń,
//	http://biblia.apologetyka.com/ (wersja 5.0 beta 7) - 92 tłumaczenia.
	public static final String SOURCE_biblia_info_pl = "http://www.biblia.net.pl/cgi-bin/biblia.cgi?";
	public static final String LOG = "BIB_WPI";
	private static final String pre_databaseFileName = "Translations.db";
	private DBAdapter db;
	private MainActivity mainActivity;
	private BibleChapter chapter;	
	
	public WebPageImporter(MainActivity main)
	{
		mainActivity = main;
		db = main.db;
		try {
			copyDB();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int importBible(int translationNumber)
	{
		db.open();
		// TODO dla kazdej wyswietlonej strony parsowanie i zapis do bazy / na jednej stronie wyswietlana zawartosc jednej ksiegi
//		for(int i=1; i<=FULL_BIBLE_BOOKS_COUNT; i++)
//		{
			int i=1;
			Log.d(LOG, "" +i);
			String bookNameShort = db.getBookAlias(i);
			String translationAlias = mainActivity.getTranslationsAliases()[translationNumber];
			String webPageSource = httpGet(createURLtoChapter(translationAlias, bookNameShort, 1));
			int translID = db.getTranslationID(translationAlias);
			BibleAddress adr = new BibleAddress(translID, i, 1, 0);
			chapter = new BibleChapter();
			chapter = prepareBibleChapter(webPageSource, adr);
			createVersesTable(translationAlias);
			saveChapterToDB(translationAlias, chapter);
//		}
		updateTranslation(translationAlias, 1);
		db.close();
		return 0;
	}
	
	private void updateTranslation(String shortName, int downloaded)
	{
		BibleTranslation t = db.getTranslation(shortName);
		db.updateTranslation(t.getFullName(), t.getShortName(), downloaded);
	}
	
	private void saveChapterToDB(String translationAlias, BibleChapter chap)
	{
		for (BibleVerse verse : chap.getVerses()) {
			db.insertVerse(translationAlias, verse.getAddress().getBook(), verse.getAddress().getChapter(), verse.getAddress().getVerse(), verse.getVerseText());
		}
	}
	
	private void createVersesTable(String translationAlias)
	{
		Log.d(LOG, "Creating table: Verses_" + translationAlias);
		db.createVersesTable(translationAlias);
	}
	
	private BibleChapter prepareBibleChapter(String pageSource, BibleAddress adr)
	{
		BibleAddress chapterAddress = adr;
		BibleVerse verse = new BibleVerse();
		String[] substrings;
		ArrayList<BibleVerse> verses = new ArrayList<BibleVerse>();
		substrings = pageSource.split("<SPAN class=\"nrWersetu\">");
		//first element of substrings[] is not important 
		for(int i=1; i<=substrings.length-1;i++)
		{
			BibleAddress a = new BibleAddress(adr.getTranslation(), adr.getBook(), adr.getChapter(), 
					Integer.valueOf(substrings[i].substring(1, substrings[i].indexOf(")"))));
			if(i==(substrings.length-1))
			{
				//	TODO
				verse = new BibleVerse(a, substrings[i].substring(substrings[i].indexOf("</SPAN>")+7, substrings[i].indexOf("<BR>")));
			}
			else
				verse = new BibleVerse(a, substrings[i].substring(substrings[i].indexOf(">")+1));
			verses.add(verse);

		}
		chapter = new BibleChapter(chapterAddress, verses);
		Log.d(LOG, chapter.toString());
		return chapter;
	}
	
	/**
	 * Method for downloading a Web page to a String by HTTP GET request
	 * @param urlString
	 * @return
	 */
	public String httpGet(String urlString)
	{
		String result = "error";
		HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        try {
			request.setURI(new URI(urlString));
	        HttpResponse response = client.execute(request);
	        result = EntityUtils.toString(response.getEntity(), "iso-8859-2");
        } catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return result;
	}

	public String createURLtoChapter(String translation, String book, int chapter)
	{
		String source = SOURCE_biblia_info_pl;
		source += book + chapter + ".1-999/t" + translation + "/o/li";
		Log.d(LOG, "datasource: " + source);
		return source;
	}
	
	public void copyDB() throws IOException
	{
		String destPath = "/data/data/" + mainActivity.getPackageName() + "/databases";
		String fileName = "Translations.db";
		File directory = new File(destPath);
		boolean test = directory.mkdirs();
		Log.d(LOG, "Directory path present: " + !test);
		File file = new File(directory, fileName);
		test = file.exists();
		Log.d(LOG, "Database file exists: " + test);
		boolean isCreated = file.createNewFile();
		Log.d(LOG, "Database file created: " + isCreated);
		if(isCreated)				// jeśli baza nie istnieje, to kopiuje
		{
			Log.d(LOG, "Copying DB...");
			InputStream inputstream = mainActivity.getBaseContext().getAssets().open(pre_databaseFileName);
			OutputStream outputstream = new FileOutputStream(file);
			
			byte[] buffer = new byte[1024];
			int length;
			while((length = inputstream.read(buffer))>0)
			{
				outputstream.write(buffer, 0, length);
			}
			inputstream.close();
			outputstream.close();
		}
	}
	
	/*
    private void saveToInternalStorage(String text)
    {
		try {
			FileOutputStream fOut;
			fOut = openFileOutput("textFile.txt", MODE_WORLD_READABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fOut);
			
			//--------write the sting to the file---------
			osw.write(text);
			osw.flush();
			osw.close();
			
			//---display file saved message---
			Toast.makeText(getBaseContext(), "Web page saved successfully", Toast.LENGTH_SHORT).show();
			translationsNumber++;
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
    }
    
    private void saveToExternalStorage(String text)
    {
    	String state = Environment.getExternalStorageState();
    	
    	if (Environment.MEDIA_MOUNTED.equals(state)) {
    	    // We can read and write the media
    	    
    	    try {
    	    	File sdCard = Environment.getExternalStorageDirectory();
    	    	File directory = new File(sdCard.getAbsolutePath() + appFolder);
    	    	boolean isPath = directory.mkdirs();
    	    	System.out.println(isPath);
//    			Toast.makeText(getBaseContext(), "Path " + String.valueOf(isPath), Toast.LENGTH_SHORT).show();
    	    	File file = new File(directory, "textFile.txt");
    	    	FileOutputStream fOut = new FileOutputStream(file);
    	    	
    	    	OutputStreamWriter osw = new OutputStreamWriter(fOut);
    			
    			//--------write the sting to the file---------
    	
    			osw.write(text);
    	
    			osw.flush();
    			osw.close();
    			
    			//---display file saved message---
    			Toast.makeText(getBaseContext(), "Web page saved successfully", Toast.LENGTH_SHORT).show();
    			translationsNumber++;
    			boolean test = addTranslationToList();
    			System.out.println(test);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    	    // We can only read the media

			Toast.makeText(getBaseContext(), state, Toast.LENGTH_LONG).show();
    	} else {
    	    // Something else is wrong. It may be one of many other states, but all we need
    	    //  to know is we can neither read nor write

			Toast.makeText(getBaseContext(), state + " Not saved!", Toast.LENGTH_LONG).show();
    	}
		
    }
    
    /**
     * adds an entry to the list file of all translations in the main app directory
     * @return
     *//*
    private boolean addTranslationToList()
    {
    	String state = Environment.getExternalStorageState();
    	
    	if (Environment.MEDIA_MOUNTED.equals(state)) {
    	    // We can read and write the media
    	    
    	    try {
    	    	File sdCard = Environment.getExternalStorageDirectory();
    	    	File directory = new File(sdCard.getAbsolutePath() + appFolder);
    	    	boolean isPath = directory.mkdirs();

    	    	File file = new File(directory, "TranslationsList.txt");
    	    	FileOutputStream fOut = new FileOutputStream(file);
    	    	
    	    	OutputStreamWriter osw = new OutputStreamWriter(fOut);
    			
    			//--------write the sting to the file---------
    	    	String entry = "<Translation no=\"" + translationsNumber +"\" title=\"Biblia 1\" path=\"textFile.txt\"";
    	
    			osw.write(entry);
    			osw.flush();
    			osw.close();
    			
    			//---display file saved message---
    			Toast.makeText(getBaseContext(), "Translation entry saved successfully", Toast.LENGTH_SHORT).show();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    	    // We can only read the media
			Toast.makeText(getBaseContext(), state, Toast.LENGTH_LONG).show();
			return false;
    	} else {
    	    // Something else is wrong. It may be one of many other states, but all we need
    	    //  to know is we can neither read nor write

			Toast.makeText(getBaseContext(), state + " Not saved!", Toast.LENGTH_LONG).show();
			return false;
    	}
		return true;
    }
    */
}

///t<xxx> - użyj wybranego tłumaczenia, w miejsce <xxx> należy wstawić:
//    bt - Biblia Tysiąclecia
//    bw - Biblia Warszawska (tzw. Brytyjska)
//    br - Biblia Warszawsko-Praska (Romaniuka)
//    bg - Biblia Gdańska
//    vl - Łacińska Vulgata
//    av - King James Version
//    wb - Webster Bible
//    yl - Young's Literal Translation
//    Domyślnie program używa Biblii Tysiąclecia.
///o      - numeruj wersety
///l<s>   - wypisz tekst w standardzie polskich liter określonym przez <s>:
//    i - ISO 8859-2; w - Windows; b - bez polskich liter
//    Domyślnie tekst wypisywany jest w ISO 8859-2 (ISO Latin 2).